package org.qee.mq.custom;

import java.io.IOException;

/**
 * @ProjectName: learning
 * @Package: org.qee.mq.custom
 * @ClassName: MqProducer
 * @Description:
 * @Date: 2021/12/20 10:33 上午
 * @Version: 1.0
 */
public class MqProducer implements Producer {

    private ValueSerialization valueSerialization;

    private Topic topic;

    public MqProducer(String topicName) {
        this(topicName, new JsonValueSerialization());
    }

    public MqProducer(String topicName, ValueSerialization valueSerialization) {
        topic = Topic.register(topicName, this);
        this.valueSerialization = valueSerialization;
    }

    @Override
    public boolean sendMsg(Object msg) {
        Message message = null;
        if (msg instanceof Message) {
            message = (Message) msg;
        } else {
            byte[] body = null;
            try {
                body = valueSerialization.serialize(msg);
            } catch (IOException e) {
                return false;
            }
            message = new Message();
            message.setSize(body.length);
            message.setBody(body);
        }
        return topic.send(message);
    }
}
